package lc.q250_300;

public class Q287 {
    public int findDuplicate(int[] nums) {
        // 二分查找，定义cnt[i]为小于或等于i的数的总数,一半一半去找
        int n = nums.length;
        int l = 1, r = n - 1, ans = -1;
        while (l <= r) {
            int mid = (l + r) / 2;
            int cnt = 0;
            for (int i = 0; i < n; i++) {
                if (nums[i] <= mid) {
                    cnt ++;
                }
            }
            if (cnt <= mid) {
                // 一半一半切分
                l = mid + 1;
            } else {
                r = mid - 1;
                ans = mid;
            }
        }
        return ans;
    }

}
